/*
 * File.cpp
 *
 *  Created on: 12 jun. 2013
 *      Author: maarten
 */

#include "File.hpp"
#include "Config.hpp"

#include <fcntl.h>
#include <unistd.h>

#define OPEN_RIGHT S_IRWXU | S_IRWXG

File::File(std::string aPath) {
	filedes = 0;
	path = aPath;
	fileIsOpen = false;
	lastBlockSize = 0;
}

File::~File() {
}

bool File::openFile() {
	//check if already opened
	if (fileIsOpen > 0) {
		return true;
	}

	if ((filedes = open(path.c_str(), OPEN_RIGHT)) < 0) {
		return false;
	}

	fileIsOpen = true;
	return true;
}

bool File::closeFile() {
	if (!fileIsOpen) {
		return false;
	}
	if (close(filedes) == -1) {
		return false;
	}

	return true;
}

bool File::isOpen() {
	return fileIsOpen;
}

std::string File::getPath() {
	return path;
}

bool File::checkFileRead() {
	if (access(path.c_str(), R_OK) == 0) {
		return true;
	} else {
		return false;
	}
}

bool File::checkFileWrite() {
	if (access(path.c_str(), W_OK) == 0) {
		return true;
	} else {
		return false;
	}
}

bool File::checkExists() {
	if (access(path.c_str(), F_OK) == 0) {
		return true;
	} else {
		return false;
	}
}

bool File::checkExtention() {
	int punt = path.find(".");
	bool filenameAllowed = false;

	for (std::string extension : Config::getInstance().getExtentions()) {
		if (path.substr(punt + 1).compare(extension) == 0) {
			filenameAllowed = true;
			break;
		}
	}

	return filenameAllowed;
}

bool File::fileRename(std::string newPath) {
	//NOT SURE AUBOUT PRECONDITIONS
	if (rename(path.c_str(), newPath.c_str()) != 0) {
		return false;
	}
	return true;
}

bool File::setNextBlock(char * aBuffer, int length) {
	if (!fileIsOpen) {
		return false;
	} else {
		if (write(filedes, aBuffer, length) < 0) {
			closeFile();
			return false;
		}
	}
	return true;
}

char * File::getNextBlock() {
	int rval;
	if (!fileIsOpen) {
	} else {
		rval = read(filedes, buffer, FILESPLIT);
		if (rval < 0) { //error reading
			closeFile();
		} else if (rval == 0) { //end of file
			lastBlockSize = rval;
		} else if (rval > 0) { //suc6 readed
			lastBlockSize = rval;
		}
	}
	return buffer;
}
